package com.daoshu.mds.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daoshu.mds.constants.*;
import com.daoshu.mds.system.mapper.RecentConcatsMapper;
import com.daoshu.mds.system.service.IOConcatsService;
import com.daoshu.mds.system.service.IPConcatsService;
import com.daoshu.mds.system.service.IRecentConcatsService;
import com.daoshu.system.bo.AccountBo;
import com.daoshu.system.bo.ContentBO;
import com.daoshu.system.bo.RecentConcatBO;
import com.daoshu.system.entity.*;
import com.daoshu.system.qo.RecentConcatsQO;
import com.daoshu.system.service.AccountFeignService;
import com.daoshu.system.service.OrgFeignService;
import com.daoshu.system.service.PersonFeignService;
import com.daoshu.system.utils.DateUtils;
import com.daoshu.system.utils.RequestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  最近联系人服务实现类
 * </p>
 *
 * @author zhaoyanjiang
 * @since 2018-09-10
 */
@Service
public class RecentConcatsServiceImpl extends ServiceImpl<RecentConcatsMapper, RecentConcatsEntity> implements IRecentConcatsService {

	@Autowired private RequestUtils userUtil;
	@Autowired private IOConcatsService oConcatsService;
	@Autowired private IPConcatsService pConcatsService;
	@Autowired private RecentConcatsMapper recentConcatsMapper;
	@Autowired private PersonFeignService personService;
	@Autowired private OrgFeignService orgService;
	@SuppressWarnings("unused")
	@Autowired private AccountFeignService accountService;
	

	@Override
	public IPage<RecentConcatBO> queryRecent(RecentConcatsQO qo) {
		if(qo == null) {
			qo = new RecentConcatsQO();
		}
		AccountBo user = userUtil.getCurrentUser();
		RecentConcatsEntity entity = new RecentConcatsEntity();
		BeanUtils.copyProperties(qo, entity);
		entity.setCreateId(user.getPersonBo().getId());
		QueryWrapper<RecentConcatsEntity> queryWrapper = new QueryWrapper<>(entity);
		queryWrapper.orderByDesc("create_time_");
		IPage<RecentConcatsEntity> recnets = null;
		if(qo.getGroup()) {
			qo.setPersonId(user.getPersonBo().getId());
			recnets = recentConcatsMapper.queryRecent(new Page<RecentConcatsEntity>(qo.getStart(), qo.getSize()), qo);
			if(recnets!=null) {
				recnets.getRecords().forEach(i->{
					if(i!=null) {
						i.setLinkType(LinkType.PERSON.getStatus());
					}
				});
			}
		}else {
			 recnets = this.page(new Page<RecentConcatsEntity>(qo.getStart(), qo.getSize()), queryWrapper);
		}
		IPage<RecentConcatBO> page = new Page<>(qo.getStart(), qo.getSize());
		page.setTotal(recnets.getTotal());
		List<String> orgIds = new ArrayList<>();
		List<String> personIds = new ArrayList<>();
		List<RecentConcatsEntity> list = Optional.ofNullable(recnets.getRecords()).orElse(new ArrayList<>());
		List<RecentConcatBO> recents = new ArrayList<>();
		list.stream().forEach(recent->{
			if(recent==null)
				return;
			RecentConcatBO temp = new RecentConcatBO();
			temp.setName(recent.getPersonName());
			temp.setConnectType(recent.getConnectType());
			temp.setConnectTypeName(recent.getConnectType()==null?"": ConnectType.getConcatType(recent.getConnectType()).getTitle());
			temp.setConcat(recent.getConcat());
			temp.setCreateTime(recent.getCreateTime());
			temp.setId(recent.getPersonId());
			temp.setConnectTimeString(DateUtils.getSubTimeString(recent.getCreateTime(), recent.getEndTime()));
			// 新增通讯状态字段
			temp.setCallType(recent.getCallType());
			temp.setCallTypeName(recent.getCallType() == null ? "" : CallType.getCallType(recent.getCallType()).getTitle());

			if(recent.getLinkType()!=null&&recent.getLinkType().equals(LinkType.ORG.getStatus())) {
				orgIds.add(recent.getPersonId());
			}else if(recent.getLinkType()!=null&&recent.getLinkType().equals(LinkType.PERSON.getStatus())) {
				personIds.add(recent.getPersonId());
			}

			recents.add(temp);
		});
		//List<ContentBO> orgs = oConcatsService.queryOrgConcat(orgIds);
		List<ContentBO> persons = pConcatsService.queryPersonConcat(personIds);
		//persons.addAll(orgs);
		persons.forEach(content -> {
			recents.forEach(recent -> {
				if(recent.getId()!=null&&content.getType()!=null&&(recent.getId().equals(content.getId())&&content.getType().equals(LinkType.PERSON.getStatus())||recent.getId().equals(content.getOrgId())&&content.getType().equals(LinkType.ORG.getStatus()))) {
					BeanUtils.copyProperties(content, recent);
					if(recent.getName()==null) {
						recent.setName(content.getName());
					}
				}
			});
		});
		page.setRecords(recents);
		return page;
	}
	@Override
	public IPage<RecentConcatBO> queryRecentSimple(RecentConcatsQO qo) {
		IPage<RecentConcatBO> page = this.queryRecent(qo);
		Optional.ofNullable(page.getRecords()).orElse(new ArrayList<>()).forEach(bo->{
			bo.setConcats(null);
			bo.setPersonConcats(null);
			bo.setOrgConcats(null);
		});
		return page;
	}
	
	@Override
	public RecentConcatsEntity addRecent(RecentConcatsEntity entity) {
		String tel = entity.getConcat();
		Integer connectType = entity.getConnectType();
		Integer callType = entity.getCallType();
		AccountBo user = userUtil.getCurrentUser();
		RecentConcatsEntity recent = new RecentConcatsEntity();
		PConcatsEntity pEntity = new PConcatsEntity();
		pEntity.setConcatNumber(tel);
		QueryWrapper<PConcatsEntity> queryWrapper = new QueryWrapper<>(pEntity);
		PConcatsEntity pConcat = pConcatsService.getOne(queryWrapper);
		recent.setConcat(tel);
		recent.setConnectType(connectType);
		recent.setCreateTime(entity.getCreateTime()==null? new Date():entity.getCreateTime());
		recent.setEndTime(entity.getEndTime());
		recent.setCreateId(user.getPersonBo().getId());
		recent.setDeviceStatus(LocalState.start.getType());
		// 新增通讯状态字段
		recent.setCallType(callType);
		if(pConcat!=null) {
			recent.setConcatId(pConcat.getId());
			recent.setConcatType(pConcat.getConcatType());
			recent.setLinkType(LinkType.PERSON.getStatus());
			recent.setPersonId(pConcat.getPersonId());
			recent.setPersonName(Optional.ofNullable(personService.getById(pConcat.getPersonId())).orElse(new PersonEntity()).getName());
		}else {
			OConcatsEntity o = new OConcatsEntity();
			o.setConcatNumber(tel);
			QueryWrapper<OConcatsEntity> queryO = new QueryWrapper<>(o);
			OConcatsEntity oConcat = oConcatsService.getOne(queryO);
			if(oConcat!=null) {
				recent.setConcatId(oConcat.getId());
				recent.setConcatType(oConcat.getConcatType());
				recent.setLinkType(LinkType.ORG.getStatus());
				recent.setPersonId(oConcat.getOrganizationId());
				recent.setPersonName(Optional.ofNullable(orgService.getById(oConcat.getOrganizationId())).orElse(new OrganizationEntity()).getName());
			}
		}
		this.save(recent);
		return recent;
	}
	@Override
	public ContentBO getByIdAndType(String id, Integer type) {
		ContentBO bo = new ContentBO();
		if(id==null) {
			return bo;
		}
		List<String> ids = new ArrayList<>(1);
		ids.add(id);
		if(type!=null&&type.equals(LinkType.PERSON.getStatus())) {
			List<ContentBO> personsContent = pConcatsService.queryPersonConcat(ids);
			if(personsContent!=null&&!personsContent.isEmpty()) {
				return personsContent.get(0);
			}
				
		}else if(type!=null&&type.equals(LinkType.ORG.getStatus())) {
			List<ContentBO> orgs = oConcatsService.queryOrgConcat(ids);
			if(orgs!=null&&!orgs.isEmpty()) {
				ContentBO content = orgs.get(0);
				return content;
			}
		}
		return bo;
	}
	@SuppressWarnings("unchecked")
	@Override
	public JSONObject statistics() {
		Date date = new Date();
		int days = 7;
		Date date1 = org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
		Date date2 = org.apache.commons.lang3.time.DateUtils.addDays(date1, -days+1);
		List<RecentConcatsEntity> records = this.list(new QueryWrapper<RecentConcatsEntity>().lambda()
				.gt(RecentConcatsEntity::getCreateTime, date2).orderByDesc(RecentConcatsEntity::getCreateTime));
		org.apache.commons.lang3.time.DateUtils.isSameDay(date1, date2);
		JSONObject json = new JSONObject();
		String keys = "";
		Integer temp = 0;
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
		for(int i = 1; i <= days; i++) {
			Date date3 = org.apache.commons.lang3.time.DateUtils.addDays(date2, i - 1);
			keys = format.format(date3);
			for(int j = records.size() -1; j >= 0; j--) {
				RecentConcatsEntity recent = records.get(j);
				temp += Optional.ofNullable(json.getInteger(keys)).orElseGet(()->0);
				if(org.apache.commons.lang3.time.DateUtils.isSameDay(recent.getCreateTime(), date3)) {
					temp += 1;
					records.remove(j);
				}else {
					break;
				}
			}
			json.put(keys, temp);
			temp = 0;
		}
		return json;
	}

	
}
